<template>
  <el-form :model="form" label-width="100px" class="mt-4" :rules="rules" ref="formRef">
    <el-form-item :label="t('当前密码')" prop="currentPassword">
      <el-input v-model="form.currentPassword" type="password" show-password />
    </el-form-item>

    <el-form-item :label="t('新密码')" prop="newPassword">
      <el-input v-model="form.newPassword" type="password" show-password />
    </el-form-item>

    <el-form-item :label="t('确认密码')" prop="confirmPassword">
      <el-input v-model="form.confirmPassword" type="password" show-password />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit">{{ t('修改密码') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from "element-plus";
import {changePassword} from "@/api/user.js";
import {useI18n} from "vue-i18n";

const {t} = useI18n()
const form = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const formRef = ref(null)

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const submit = async () => {
  await formRef.value.validate()
  let res = await changePassword(form.value)
  if (res.code !== 200) {
    ElMessage.error(res.message)
    return
  }
  ElMessage.success('密码修改成功')
  formRef.value.resetFields()
}
</script>